﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Timers;

namespace HB.Base
{
    /// <summary>
    /// 平均速度
    /// </summary>
    public class AverageSpeed : IDisposable
    {
        /// <summary>
        /// 当速度发生变化时（1秒统计周期）
        /// </summary>
        public event Action<double> OnSpeedChanged;
        int[] data = null;
        int Second = 0;
        int Temp = 0;
        int CurrPtr = 0;
        Timer timer = null;
        /// <summary>
        /// 
        /// </summary>
        /// <param name="second">缓冲秒</param>
        public AverageSpeed(int second)
        {
            if (second < 1) { throw new Exception("Second Error"); }
            data = new int[second];
            this.Second = second;
            timer = new Timer();
            timer.Interval = 1000;
            timer.Elapsed += Timer_Elapsed;
            timer.Start();
        }

        private void Timer_Elapsed(object sender, ElapsedEventArgs e)
        {
            int v = Temp;
            Temp = 0;
            data[CurrPtr] = v;
            CurrPtr++;
            if (CurrPtr >= Second) { CurrPtr = 0; }
            if (OnSpeedChanged != null)
            {
                OnSpeedChanged(data.Average());
            }

        }

        /// <summary>
        /// 快速记录事件
        /// </summary>
        /// <param name="times"></param>
        public void Log(int times = 1)
        {
            Temp += times;
        }
        /// <summary>
        /// 释放
        /// </summary>
        public void Dispose()
        {
            timer.Elapsed -= Timer_Elapsed;
            timer.Stop();
        }

        /// <summary>
        /// 平均速率
        /// </summary>
        public double Speed => data.Average();
    }
}
